package com.allm.ai.common.repository;

import com.allm.ai.common.entity.ConversationMessage;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface ConversationMessageRepository extends JpaRepository<ConversationMessage, Long> {
    
    /**
     * 根据对话ID和轮次编号获取消息，按消息顺序排序
     */
    List<ConversationMessage> findByConversationIdAndRoundNumberOrderByMessageOrderAsc(String conversationId, Integer roundNumber);
    
    /**
     * 根据对话ID获取所有消息，按轮次和消息顺序排序
     */
    List<ConversationMessage> findByConversationIdOrderByRoundNumberAscMessageOrderAsc(String conversationId);
    
    /**
     * 根据模型对话ID获取消息，按消息顺序排序
     */
    List<ConversationMessage> findByModelConversationIdOrderByMessageOrderAsc(String modelConversationId);
    
    /**
     * 根据对话ID和角色获取消息
     */
    List<ConversationMessage> findByConversationIdAndRoleOrderByRoundNumberAscMessageOrderAsc(String conversationId, ConversationMessage.MessageRole role);
    
    /**
     * 根据对话ID获取最新消息
     */
    @Query("SELECT cm FROM ConversationMessage cm WHERE cm.conversationId = :conversationId ORDER BY cm.roundNumber DESC, cm.messageOrder DESC")
    List<ConversationMessage> findLatestByConversationId(@Param("conversationId") String conversationId);
    
    /**
     * 统计对话中的消息数量
     */
    long countByConversationId(String conversationId);
    
    /**
     * 根据对话ID删除所有消息
     */
    void deleteByConversationId(String conversationId);

    /**
     * 获取对话的下一个消息顺序
     */
    @Query("SELECT COALESCE(MAX(cm.messageOrder), 0) + 1 FROM ConversationMessage cm WHERE cm.conversationId = :conversationId")
    Integer getNextMessageOrder(@Param("conversationId") String conversationId);
}
